import React from 'react';
import {connect} from 'dva';
import styles from './detailPage.css';
import PoetryCard from "../components/detail/PoetryCard";
import RenderButton from "../components/detail/RenderButton";
import domtoimage from 'dom-to-image';
import PreImg from "../components/detail/PreImg";
import TextCard from "../components/detail/TextCard";
import SimpleToast from "../components/toast/SimpleToast";
import TextInfo from "../components/poetry/TextInfo";


const toastMsg = ['图片已生成，点击or长按图片即可实现下载', '悲催了，图片生成失败，请稍后再试!'];

function DetailPage({dispatch, detail, count}) {
  function loadPoetry(pid) { // 根据诗词ID获取对应的数据
    dispatch({
      type: 'detail/fetch',
      payload: pid,
    })
  }

  let {author, content, title, explain, pic, cardTitle} = detail;
  let {accessCount} = count;
  const {preVisible, preImgUrl, toastType} = detail;

  let noExplain = false;

  if (!explain) {
    noExplain = true;
    explain = '\n暂无诗词释意~~';
  }

  function handleRender() {
    const node = document.getElementById('poetryCard');
    domtoimage.toPng(node)
      .then(function (dataUrl) {
        dispatch({
          type: 'detail/updatePreUrl',
          payload: dataUrl,
        });
      })
      .catch(function (error) {
        console.error('oops, something went wrong!', error);
        // 显示失败的弹窗提醒
        dispatch({
          type: 'detail/hideOrShowToast',
          payload: 2,
        })
      });
  }

  function handleHideToast() {
    // 关闭弹窗
    dispatch({
      type: 'detail/hideOrShowToast',
      payload: null,
    })
  }

  function handleCancel() {
    dispatch({
      type: 'detail/hideOrShowPre',
      payload: false,
    })
  }

  return (
    <div className={styles["detail-container"]}>
      <TextInfo info={'中华诗选'} sub={'每日精选12首精美古诗'} toTop={true} styles={{
        textAlign: 'center',
        margin: '1em 1em 0.8em 0em',
        fontSize: '1.7em',
        width: '90%',
        textShadow: '0.5em 0.2em 0.1em #c3c2c2',
        color: '#6b6a6a',
      }}/>

      {/* 图文诗词卡片 */}
      <PoetryCard
        cardTitle={cardTitle}
        title={title}
        author={author}
        content={content}
        pic={pic}
        initPoetry={loadPoetry}
      />

      <TextCard cardTitle={'注释'}
                cardContent={explain}
                defaultContent={noExplain}/>

      <TextInfo sub={'古诗选 | Zweb+ © 2017~2018 | YiHui | 本站总访问: ' + accessCount.total} subStyles={{
        textAlign: 'center',
        paddingTop: '2em',
      }}/>

      {/*渲染后的预览图*/}
      <PreImg cancel={handleCancel} src={preImgUrl} visible={preVisible}/>

      {toastType ? <SimpleToast cancel={handleHideToast} info={toastMsg[toastType - 1]}/> : null}

      {/* 渲染按钮*/}
      <RenderButton render={handleRender}/>
    </div>
  );
}

DetailPage.propTypes = {};

function mapStateToProps({detail, count}) {
  return {detail, count};
}

export default connect(mapStateToProps)(DetailPage);
